package com.hmdp.utils;

import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;

@Component
public class RedisIdWorker {
    private static final long BEGIN_TIMESTAMP = 1640995200L;
    private static final int COUNT_BITS = 32;
    private StringRedisTemplate stringRedisTemplate;

    public RedisIdWorker(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }

    public static void main(String[] args) {
        LocalDateTime time = LocalDateTime.of(2024, 1, 1, 0, 0, 0);
        long second = time.toEpochSecond(ZoneOffset.UTC);
        System.out.println(second);
    }

    public long nextId(String keyPrefix) {
        // 1. 生成时间戳
        LocalDateTime now = LocalDateTime.now(); // 获取当前时间
        long nowSecond = now.toEpochSecond(ZoneOffset.UTC); // 将当前时间转换为自1970-01-01以来的秒数
        long timestamp = nowSecond - BEGIN_TIMESTAMP; // 计算相对于自定义开始时间戳的时间差

        // 2. 生成序列号
        String date = now.format(DateTimeFormatter.ofPattern("yyyyMMdd")); // 将当前日期格式化为"yyyyMMdd"
        long count = stringRedisTemplate.opsForValue().increment("icr:" + keyPrefix + ":" + date); // 在Redis中自增并获取序列号

        // 3. 拼接并返回
        return timestamp << COUNT_BITS | count; // 将时间戳左移指定位数，并与序列号进行按位或操作，生成唯一ID
    }

}
